package ru.ifmo.mlarinsky.classificator.xml;

import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import ru.ifmo.mlarinsky.classificator.io.ClassificatorRuntimeException;

public abstract class XMLBuilder {

    public String buildXMLString(Object data) {
        try {
            DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
            Document document = docBuilder.newDocument();

            Element rootElement = buildRootElement(document, data);
            document.appendChild(rootElement);

            TransformerFactory transfac = TransformerFactory.newInstance();
            Transformer transformer = transfac.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");

            StringWriter sw = new StringWriter();
            StreamResult result = new StreamResult(sw);
            DOMSource source = new DOMSource(document);
            transformer.transform(source, result);

            String header = buildHeader();

            return header + sw.toString();
        } catch (Exception e) {
            throw new ClassificatorRuntimeException("Failed to build xml.", e);
        }
    }

    protected abstract Element buildRootElement(Document document, Object dataProvider)
            throws IllegalArgumentException;

    protected abstract String buildHeader();
}
